import { ref, reactive } from 'vue';
import { update, submit, query, one } from '@/chaos/functions/common/Data';

export default function useUpdateForm(
    domain,
    search,
    showUpdateMethod,
    updateMethod
) {
    const showUpdateForm = ref(false);
    const updateFormRef = ref(null);
    let updateForm = reactive({});

    const showUpdate = async mu => {
        showUpdateForm.value = true;
        if (showUpdateMethod) {
            updateForm = reactive(
                await query(`${domain}/${showUpdateMethod}`, { mu })
            );
        } else {
            const res = await one(domain, mu);
            for (let key in res) {
                updateForm[key] = res[key];
            }
        }
    };
    const doUpdate = () => {
        updateFormRef.value.validate(async valid => {
            if (!valid) {
                return false;
            }
            let res;
            if (updateMethod) {
                res = await submit(`${domain}/${updateMethod}`, {
                    mu: updateForm.mu,
                    data: updateForm
                });
            } else {
                res = await update(domain, updateForm.mu, updateForm);
            }
            if (res) {
                showUpdateForm.value = false;
                search();
            }
        });
    };
    return { showUpdateForm, updateForm, updateFormRef, showUpdate, doUpdate };
}
